<template>
    <div>
      <el-dialog
        title="添加联系人"
        v-model="chatStor.state.showAddContactsDialog"
        width="50%"
      >
        <div style="display: flex; align-items: center; gap: 10px;">
            <el-input
              placeholder="输入用户的网盘ID,网盘ID在个人中心中可以查看"
              prefix-icon="el-icon-search"
              v-model="searchText"
            />
            <el-button type="primary" @click="searchContact" >搜索</el-button>
        </div>
        
        <el-radio-group v-model="selectedContact">
          <el-radio
            v-for="(contact, index) in currentContacts"
            :key="index"
            :label="contact"
            style="height: 100px;"
          >
            <img :src="contact.avatar"  style="width: 30px; height: 30px; margin-right: 10px">
            {{contact.username}}
          </el-radio>
        </el-radio-group>
        <div >
          <el-button @click="CancelDialog">取消</el-button>
          <el-button type="success" @click="handleConfirm">确认</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {chatStore} from '@/stores/disk/chat'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {searchContactById,isAddContact,addContact} from '@/api/disk/user'
const chatStor=chatStore()
//搜索文本
const searchText=ref('')
//联系人列表
const currentContacts=ref([])
//选择的联系人
const selectedContact=ref(null)


//搜索联系人
const searchContact=async () => {
  currentContacts.value=[]
  const text=searchText.value
  if(text===''){
      ElMessage.error('请输入用户的网盘ID');
      return;
  }
  //判断id是否为自己的id
  const userId = localStorage.getItem('userId');
  if(text===userId){
      ElMessage.error('不能添加自己为联系人');
      return;
  }
  //发起请求
  const res = await searchContactById(text)
  currentContacts.value.push(res.data)
}

//确认添加联系人
const handleConfirm=async () => {
  if(selectedContact.value===null){
    ElMessage.error('请选择联系人');
    return;
  }
  //判断是否选择了联系人
  const data={
    userOther:selectedContact.value.id,
    userSelf:localStorage.getItem('userId'),
    status:0,
    contactName:selectedContact.value.username,
  }
  const res = await isAddContact(data)
  if(res.data===0){
    //添加过
    ElMessage.error('该联系人已添加过');
    return;
  }else{
    //未添加
    const temp={
      contactName:selectedContact.value.username,
      userOther:selectedContact.value.id,
      userSelf:parseInt(localStorage.getItem('userId')),
      status:0,
    }
    await addContact(temp)
    //刷新联系人列表
    chatStor.getContacts()
    //关闭弹窗
    chatStor.updateShowAddContactsDialog(false)
    ElMessage.success('添加成功');
  }

}
//取消添加联系人
const CancelDialog=() => {

}
</script>

<style scoped>

</style>